package hung.vnptthanhhoa.util;

import hung.vnptthanhhoa.adapter.CookingList;

import java.util.ArrayList;

import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBCooking extends SQLiteOpenHelper {

	public DBCooking(Context context) {
		super(context, "forwoman_loaimonan", null,5);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		String query = "CREATE TABLE  forwoman_loaimonan  ( id 	INTEGER NOT NULL PRIMARY KEY,name TEXT,image varchar,count INTEGER)";
		db.execSQL(query);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String query = "DROP TABLE IF EXISTS forwoman_loaimonan";
		db.execSQL(query);
		onCreate(db);

	}

	public boolean insertLoaiMonAn(JSONObject queryValue) {

		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues contentValue = new ContentValues();
		try {
			int count = getCount(queryValue.getInt("id"));
			contentValue.put("id", queryValue.getInt("id"));
			contentValue.put("name", queryValue.getString("name"));
			contentValue.put("image", queryValue.getString("image"));
			contentValue.put("count", queryValue.getInt("count"));

			if (count > 0) {
				db.update("forwoman_loaimonan", contentValue, "id = "
						+ queryValue.getInt("id"), null);
			} else {
				db.insert("forwoman_loaimonan", null, contentValue);
			}
		} catch (Exception e) {
			Log.e("Lỗi", "Lỗi insert dữ liệu");
			return false;
		}
		db.close();
		return true;

	}

	public int getCount(int id) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"SELECT id FROM forwoman_loaimonan where id = " + id, null);
		return cursor.getCount();
	}

	public ArrayList<CookingList> getArrayList() {

		ArrayList<CookingList> arrayList = new ArrayList<CookingList>();
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT * FROM forwoman_loaimonan", null);
		if (cursor.moveToFirst()) {
			do {
				CookingList cookingList = new CookingList(
						Integer.parseInt(cursor.getString(0)),
						cursor.getString(1), cursor.getString(2),
						Integer.parseInt(cursor.getString(3)));
				arrayList.add(cookingList);
			} while (cursor.moveToNext());
		}
		db.close();
		return arrayList;
	}
}
